﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DAMS.Models;
using DAMS.Service;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace DAMS.Web.Areas.Manage.Controllers
{
    [Area("Manage")]
    public class HomeController : Controller
    {

        private readonly IRepository _repo;
        private readonly IHostingEnvironment _env;
        private readonly SiteConfig _config;

        public HomeController(IRepository repository, IHostingEnvironment env, IOptions<SiteConfig> option)
        {
            this._repo = repository;
            this._env = env;
            this._config = option.Value;
        }

        public IActionResult upImage()
        {
            return View();
        }

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public IActionResult UpLoadFile(IFormFile imgFile,string dir)
        {
            string upLoadDir = "upLoad";
            if (!string.IsNullOrWhiteSpace(dir))
            {
                if("image,flash,media,file".IndexOf(dir.ToLower())!=-1)
                {
                    upLoadDir = Path.Combine(upLoadDir, dir);
                }
            }
            string extFileName = Path.GetExtension(imgFile.FileName);//文件扩展名
            if(string.IsNullOrEmpty(extFileName))//检查扩展名是否为空，为空则根据文件类型设置扩展名
            {
                if(_config.AllowImageType.IndexOf(imgFile.ContentType.ToLower())>0)
                {
                    extFileName='.' +imgFile.ContentType.Split('/')[1];
                }
                
            }
            string fileName = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString().Substring(0, 8) + extFileName;
            //检查目录是否存在
            string path = Path.Combine(_env.WebRootPath, upLoadDir);
            if(!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (var stream = new FileStream(Path.Combine(path,fileName), FileMode.Create))
            {
                imgFile.CopyTo(stream);
            }

            upLoadDir = upLoadDir.Replace("\\", "/");
            string url = Url.Content($"~/{upLoadDir}/{fileName}");
            var result = new { error = 0, Url = url };
            return Json(result);

        }
        [HttpPost]
        public IActionResult ckUpLoadFile(IFormFile upload, string dir)
        {
            string upLoadDir = "upLoad";
            if (!string.IsNullOrWhiteSpace(dir))
            {
                if ("image,flash,media,file".IndexOf(dir.ToLower()) != -1)
                {
                    upLoadDir = Path.Combine(upLoadDir, dir);
                }
            }
            string extFileName = Path.GetExtension(upload.FileName);//文件扩展名
            string fileName = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString().Substring(0, 8) + extFileName;
            //检查目录是否存在
            string path = Path.Combine(_env.WebRootPath, upLoadDir);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (var stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                upload.CopyTo(stream);
            }

            upLoadDir = upLoadDir.Replace("\\", "/");
            string url = Url.Content($"~/{upLoadDir}/{fileName}");
            var result = new {
                uploaded = 1,
                FileName=fileName,
                Url = url };
            return Json(result);

        }
        public IActionResult ckFilesManage()
        {
            return Ok();
        }

        public IActionResult UpLoadFileManage()
        {
            //String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);

            //根目录路径，相对路径
            string rootPath = _env.WebRootPath;
            //根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
            string rootUrl = "/upLoad";
            //图片扩展名
            string fileTypes = "gif,jpg,jpeg,png,bmp";

            string currentPath = "";
            string currentUrl = "";
            string currentDirPath = "";
            string moveupDirPath = "";

            string dirPath = Path.Combine(rootPath, "upLoad");
            string dirName = Request.Query["dir"];
            if (!String.IsNullOrEmpty(dirName))
            {
                if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1)
                {
                    return Content("Invalid Directory name.");
                }
                dirPath = Path.Combine(dirPath,dirName);
                rootUrl =rootUrl+ "/" + dirName +"/";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
            }

            //根据path参数，设置各路径和URL
            string path = Request.Query["path"]; ;
            path = string.IsNullOrEmpty(path) ? "" : path;
            if (path == "")
            {
                currentPath = dirPath;
                currentUrl = rootUrl;
                currentDirPath = "";
                moveupDirPath = "";
            }
            else
            {
                currentPath = rootUrl + path;
                currentPath=currentPath.Remove(0, 1);
                currentPath =Path.Combine(rootPath, currentPath.Replace("\\", "/"));
                currentUrl = rootUrl + path;
                currentDirPath = path;
                moveupDirPath = System.Text.RegularExpressions.Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1");
            }
            //排序形式，name or size or type
            string order = Request.Query["order"];
            order = String.IsNullOrEmpty(order) ? "" : order.ToLower();

            //不允许使用..移动到上一级目录
            if (System.Text.RegularExpressions.Regex.IsMatch(path, @"\.\."))
            {
                return Content("Access is not allowed.");
            }
            //最后一个字符不是/
            if (path != "" && !path.EndsWith("/"))
            {
                return Content("Parameter is not valid.");
            }
            //目录不存在或不是目录
            if (!Directory.Exists(currentPath))
            {
                return Content("Directory does not exist.");
            }

            //遍历目录取得文件信息
            string[] dirList = Directory.GetDirectories(currentPath);
            string[] fileList = Directory.GetFiles(currentPath);
            /*
            switch (order)
            {
                case "size":
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new SizeSorter());
                    break;
                case "type":
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new TypeSorter());
                    break;
                case "name":
                default:
                    Array.Sort(dirList, new NameSorter());
                    Array.Sort(fileList, new NameSorter());
                    break;
            }
            */
            System.Collections.Hashtable result = new System.Collections.Hashtable();
            result["moveup_dir_path"] = moveupDirPath;
            result["current_dir_path"] = currentDirPath;
            result["current_url"] = currentUrl;
            result["total_count"] = dirList.Length + fileList.Length;
            List<System.Collections.Hashtable> dirFileList = new List<System.Collections.Hashtable>();
            result["file_list"] = dirFileList;
            for (int i = 0; i < dirList.Length; i++)
            {
                DirectoryInfo dir = new DirectoryInfo(dirList[i]);
                Hashtable hash = new Hashtable();
                hash["is_dir"] = true;
                hash["has_file"] = (dir.GetFileSystemInfos().Length > 0);
                hash["filesize"] = 0;
                hash["is_photo"] = false;
                hash["filetype"] = "";
                hash["filename"] = dir.Name;
                hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                dirFileList.Add(hash);
            }
            for (int i = 0; i < fileList.Length; i++)
            {
                FileInfo file = new FileInfo(fileList[i]);
                Hashtable hash = new Hashtable();
                hash["is_dir"] = false;
                hash["has_file"] = false;
                hash["filesize"] = file.Length;
                hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
                hash["filetype"] = file.Extension.Substring(1);
                hash["filename"] = file.Name;
                hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
                dirFileList.Add(hash);
            }
            return Json(result);
        }
    }

    
}